[Numpy] Variable、Tensor、Numpy的转换 您所在的位置:网站首页 tensor numpy转换 [Numpy] Variable、Tensor、Numpy的转换

[Numpy] Variable、Tensor、Numpy的转换

2023-10-07 15:43| 来源: 网络整理| 查看: 265

Tensor Numpy

Tensor与Numpy之间可以相互转换: 代码:

import torch import numpy as np data = np.array([[1,2,3,4,5],[6,7,8,9,10]]) print(data) # numpy -> tensor data_tensor = torch.from_numpy(data) print(data_tensor) # tensor -> numpy data_numpy = data_tensor.numpy() print(data_numpy)

输出:

[[ 1 2 3 4 5] [ 6 7 8 9 10]] tensor([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10]], dtype=torch.int32) [[ 1 2 3 4 5] [ 6 7 8 9 10]] Variable -> Numpy

Variable可以直接转为Numpy:

import torch from torch.autograd import Variable # 定义一个Variable data = Variable(torch.Tensor([4]),requires_grad = True) # Variable -> Numpy data_numpy = data.detach().numpy() print('Numpy:',data_numpy)

如果把requires_grad改为False,得到的是Tensor:

data_false = Variable(data_tensor,requires_grad = False) print(data_false)

输出:

tensor([4.]) Numpy ->Tensor -> Variable

但是Numpy不可以直接转为Variable,所以要借助Tensor进行转换:

# Numpy --> Variable ( Numpy ->Tensor -> Variable ) # 1. Numpy ->Tensor data_tensor = torch.from_numpy(data_numpy) print('Tensor:',data_tensor) # 2. Tensor -> Variable data_Variable = Variable(data_tensor,requires_grad = True) print('Variable:',data_Variable)

输出:

Numpy: [4.] Tensor: tensor([4.]) Variable: tensor([4.], requires_grad=True)

若试图直接将Numpy转为Variable,data_Variable = Variable(data_numpy),会出现如下错误: 在这里插入图片描述

[1] PyTorch 入门实战(二)——Variable(六、Variable转Numpy与Numpy转Variable):https://blog.csdn.net/qq_36556893/article/details/86490458#%E5%85%AD%E3%80%81Variable%E8%BD%ACNumpy%E4%B8%8ENumpy%E8%BD%ACVariable



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有